<template>
<!-- 用到了 -->

<!-- 预览问卷 -->
    <div style="padding: 10px">        
        <!-- 回到顶部 -->
        <template>
            <el-backtop :bottom="100"></el-backtop>
        </template>
        <el-header>
            <el-menu  id="main1-menu"  class="el-menu-demo" mode="horizontal"
                active-text-color="#E6A23C">        
                <div style="float:right;padding:15px 50px;">
                    <router-link to="/book">
                        <el-button round>返回问卷库</el-button>
                    </router-link>                                      
                </div>
            </el-menu>
        </el-header>
        <div class="title">
            <h2>{{stitle}}</h2>            
        </div>
        <div class="temp1"></div>
        <div>            
            <el-card class="context" shadow="always">
                <div class="survey-form">
                    <el-form id="surveyData" ref="surveyData" :rules="rules"  :model="surveyData">

                        <div v-if="questions.length===0">
                            <h2>该问卷暂无问题</h2>
                        </div>

                        <el-form-item v-for="(question,i) in questions" :key="i" :prop="'res['+i+'].answer'">
                            <div class="qtitle-css" v-if="question.type===1">{{i+1}}、{{question.questionName}}{{'('+danxuanti+')'}}</div>
                            <div class="qtitle-css" v-if="question.type===2">{{i+1}}、{{question.questionName}}{{'('+duoxuanti+')'}}</div>
                            <div class="qtitle-css" v-if="question.type===3">{{i+1}}、{{question.questionName}}{{'('+tiankong+')'}}</div>


                            <!-- 单选题 -->
                            <div v-if="question.type===1 && question.id===surveyData.res[i].id" style="width:80%;">
                                <span v-for="(op,index) in question.optionData" :key="index">
                                    <el-radio v-model="surveyData.res[i].answer" :label="op.id">{{op.optionName}}&nbsp;&nbsp;&nbsp;</el-radio>
                                </span>
                            </div>
                            <!-- 多选题 -->
                            <div v-if="question.type===2 && question.id===surveyData.res[i].id" style="width:80%;">
                                <el-checkbox-group v-model="surveyData.res[i].answer">
                                    <span v-for="op in question.optionData" :key="op" style="width:80%;">
                                        <el-checkbox :label="op.id">{{op.optionName}}&nbsp;&nbsp;&nbsp;</el-checkbox>
                                    </span>
                                </el-checkbox-group>
                            </div>
                            <!-- 简答题 -->
                            <div v-if="question.type===3 && question.id===surveyData.res[i].id">
                                <el-input type="textarea" v-model="surveyData.res[i].answer" show-word-limit style="width:400px;" placeholder="请输入"></el-input>
                            </div>
                        </el-form-item>

                         <el-form-item>
                            <el-row style="width:75%;text-align:center;">
                                <el-button v-if="this.publish===2" type="warning" @click="submitSurvey">提交</el-button>
                            </el-row>
                        </el-form-item>
                    </el-form>
                </div>
            </el-card>
        </div>

        <el-dialog title="提示" v-model="dialogVisible1" v-if="islogin==null" width="30%" customClass="my-info-dialog">
        <el-form :model="form" label-width="120px">
          <el-form-item label="用户名">
            <el-input v-model="form.userAccount" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.passWord" style="width: 80%"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible1 = false">取 消</el-button>
            <el-button type="primary" @click="save1">确 定</el-button>
          </span>
        </template>
      </el-dialog>


    </div>
</template>


<script>
import axios from 'axios';
export default {
    data(){     
        var checkAnswer = (rule, value, callback) => {
            if (value === '') {
                return callback(new Error('这一题还没有填哦！'));
            }else{
                callback();
            }
        };   
        return {
            islogin:sessionStorage.getItem('useraccount'),
            dialogVisible1:true,
            danxuanti:"单选题",
            duoxuanti:"多选题",
            tiankong:"填空题",
            id: this.$route.query.id,
            form:{
                options:''
            },
            surveyData:{
                id: 1,//问题id
                userid:'',//用户id
                questionnaireid:1,//问卷id
                res:[]
            },
            rules:{
                res:[]
            },
            stitle: '',
            publish:1,
            questions: []
        }
    },
    methods:{

        //加载问卷内容
        loadSurveyInfo(){
            // console.log(this.sid)
            // if(this.sid > 0){
            //     this.axios.post('/api/surveyPage',{
            //         sid: this.sid
            //      })
            //     .then(res => {
            //         console.log(res)
            //         if (res.status===200) {
            //             this.stitle = res.data.stitle;                        
            //             document.title = '预览—'+this.stitle;
            //             this.surveyData.sid = this.sid;
            //             this.questions = res.data.questions;
            //             this.questions.forEach(element => {
            //                 if (element.qtype === 2) {
            //                     //多选题，添加的回答数据结构为数组
            //                     this.surveyData.res.push({
            //                         qid:element.qid,
            //                         qtype: element.qtype,
            //                         answer:[]
            //                     });
            //                 }else{
            //                     this.surveyData.res.push({
            //                         qid:element.qid,
            //                         qtype: element.qtype,
            //                         answer:''
            //                     });
            //                 } 
            //                 this.rules.res.push({
            //                     answer:[{required: true, validator: this.checkAnswer,message:"这一题还没有填哦！", trigger: 'blur'}]
            //                 });    
            //             });
            //             console.log(this.surveyData.res)
            //         }
            //     })
            //     .catch(err => {
            //         console.error(err); 
            //     })
            // }
            const _this=this
            axios({
                // url:'http://uchiha.vip:5000/questionnaireContent/?questionnaireId='+this.$route.query.id,
                url:'/questionnaireContent/?questionnaireId='+this.$route.query.id,

                method:"get",
            }).then(function(res){
                    console.log(res.data)
                    if(res.data.msg=='上传成功'){
                        console.log(5555)
                       // console.log(res.data.data[0].id)
                        _this.surveyData.id=res.data.data.id;
                        _this.questions=res.data.data;
                        //console.log(_this.questions)
                        _this.questions.forEach(element=>{
                            if(element.type==2){
                                _this.surveyData.res.push({
                                    id:element.id,
                                    type: element.type,
                                    answer:[]
                                });
                            }
                            else{
                                _this.surveyData.res.push({
                                    id:element.id,
                                    type: element.type,
                                    answer:''
                                });
                            }
                           //  this.rules.res.push({
                           //         answer:[{required: true, validator: this.checkAnswer,message:"这一题还没有填哦！", trigger: 'blur'}]
                           //     });    
                        });
                        _this.surveyData.userid=sessionStorage.getItem('useraccount')
                        _this.surveyData.questionnaireid=Number(_this.$route.query.id)
                    }
            })

        },

          // 问卷标题 已完成
        getTitle(){
            const _this=this
            axios({
                // url:'http://uchiha.vip:5000/questionnaire/?id='+this.$route.query.id,
                url:'/questionnaire/?id='+this.$route.query.id
            }).then(function(resp){
                _this.stitle=resp.data.data[0].questionTitle
                sessionStorage.setItem('stitle',resp.data.data[0].questionTitle)
            })
        },

        //弹出登录
        save1(){
              const _this=this//回调函数
             axios({
               method:"get",
            //   url:"http://uchiha.vip:5000/userAccount/?userAccount="+this.form.userAccount+"&passWord="+this.form.passWord,
              url:"/userAccount/?userAccount="+this.form.userAccount+"&passWord="+this.form.passWord,
          }).then(function (resp){
              console.log(resp)

              console.log(_this.form.userAccount)
             _this.dialogVisible1=false
              sessionStorage.setItem("useraccount",_this.form.userAccount)
              sessionStorage.setItem("passWord",_this.form.passWord)
              sessionStorage.setItem('token',resp.data.data)
          })
        },

        //获取是否公开
        isPublish(){
            const _this=this//回调函数
             axios({
               method:"get",
            //   url:"http://uchiha.vip:5000/questionnaire/?id="+this.$route.query.id,
              url:"/questionnaire/?id="+this.$route.query.id,
          }).then(function (resp){
              console.log('666'+resp.data.data[0].status)
             _this.publish=resp.data.data[0].status
          })
            
        },
        //提交问卷
        submitSurvey(){
           
          // console.log((JSON.stringify(this.surveyData)))
          console.log(JSON.stringify(this.surveyData))
          //  const a=JSON.stringify(this.surveyData.res ).replace(/[\\]/g,'')
         //    const data1={"userid":this.surveyData.userid,"questionnaireid":this.$route.query.id,"res":a}
           // console.log('555'+JSON.stringify(data1))
            // console.log(data1)
            console.log(typeof(JSON.stringify(this.surveyData)))
            const _this=this;
            axios({
                // url:'http://uchiha.vip:5000/commit',
                url:'/commit',
                method:'post',
                headers:{
                'Content-Type':'application/json; charset=utf8'
                },
                crossDomain: true,

                data:JSON.stringify(this.surveyData)
            }).then(function(resp){
                console.log(resp)
                console.log(resp.data.msg)
                if(resp.data.msg=='不可重复提交'){
                     _this.$message({
                        type:'warning',
                        message: "不可重复提交"
                    })
                    _this.$refs['surveyData'].resetFields()
                return;
                }
                 _this.$message({
                        type:'info',
                        message: "提交成功"
                    })
                _this.$refs['surveyData'].resetFields()
            })


            // this.$refs[surveyData].validate((valid) => {
            //     if (valid) {
            //         console.log(JSON.stringify(this.surveyData))
            //         this.axios.post("api/submitRes",JSON.stringify(this.surveyData))
            //         .then(res => {
            //             console.log(res)
            //             if (res.status===200) {
            //                 if (res.data.msg==="success") {
            //                     //显示操作成功对话框
            //                     this.msgSuccessShow();
            //                 }else{
            //                     //显示操作失败对话框
            //                     this.msgFailShow();
            //                 }
            //             }
            //         })
                    
            //         .catch(err => {
            //             console.error(err); 
            //         })
            //     } else {
            //         this.$message({
            //             type:'warning',
            //             message: "还有问题没有做哦，回去检查看看吧~"
            //         })
            //         return false;
            //     }
            // });

        }


    },
    mounted(){
        this.loadSurveyInfo();
       this.getTitle();
       this.isPublish();
    }
}
</script>
<style >

/* background-color: #ecf5ff; */

/* --el-dialog-background-color: #f4f4f5; */

 /*标题背景色*/
  .my-info-dialog .el-dialog__header  {
    background-color: #fdf6ec;
  }
  /*body背景色*/
  .my-info-dialog .el-dialog__body  {
    background-color: #fdf6ec;
  }
   .my-info-dialog .el-dialog__footer  {
    background-color: #fdf6ec;
  }
</style>